package com.atguigu.day10;

import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.kafka.clients.producer.ProducerConfig;

/**
 * @author Felix
 * @date 2024/4/12
 * 该案例演示了KafkaSink的两阶段提交
 * 要想保证写入的精准一次，需要做如下设置
 *      开启检查点
 *      .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
 *      .setTransactionalIdPrefix("flink01_2pc_sink_")
 *      设置事务超时时间  .setProperty(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG,15*60*1000 + "")
 *             检查点超时时间 < 事务超时时间 <= 事务最大超时时间(默认15分钟)
 *      在消费端，需要设置隔离级别
 *          .setProperty(ConsumerConfig.ISOLATION_LEVEL_CONFIG,"read_committed")
 *
 */
public class Flink01_2pc_sink {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(1);
        env.enableCheckpointing(10000L, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        //TODO 2.从指定的网络端口中读取数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        //TODO 3.将读取的数据写到kafka主题中
        KafkaSink<String> sink = KafkaSink.<String>builder()
                .setBootstrapServers("hadoop102:9092")
                .setRecordSerializer(KafkaRecordSerializationSchema.builder()
                        .setTopic("first")
                        .setValueSerializationSchema(new SimpleStringSchema())
                        .build()
                )
                .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
                .setTransactionalIdPrefix("flink01_2pc_sink_")
                .setProperty(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG,15*60*1000 + "")
                .build();

        socketDS.sinkTo(sink);
        //TODO 4.提交作业
        env.execute();
    }

}
